extends Node2D
class_name BaseWeapon

const _pre_bullet = preload("res://scene/bullet/BaseBullet.tscn")

var weapon_name = GameProperties.get_weapon_property("weapon_name") # 武器名称
var bullet_max = GameProperties.get_weapon_property("bullet_max") # 最大子弹数量
var damage = GameProperties.get_weapon_property("damage") # 子弹伤害
var weapon_rof = GameProperties.get_weapon_property("weapon_rof") # 武器射速
var pellet_count = GameProperties.get_weapon_property("pellet_count") # 子弹数量
var total_spread_angle = GameProperties.get_weapon_property("total_spread_angle") # 总散射角度
var random_offset = GameProperties.get_weapon_property("random_offset") # 随机偏移
var min_delay = GameProperties.get_weapon_property("min_delay")#  最小发射延
var max_delay = GameProperties.get_weapon_property("max_delay")  # 最大发射延迟（秒）
var chaos_bullet =GameProperties.get_weapon_property("chaos_bullet")  #混乱子弹概率

var parallel_bullets = GameProperties.get_weapon_property("parallel_bullets")  # 每组平行子弹数量
var parallel_spacing = GameProperties.get_weapon_property("parallel_spacing")  # 平行子弹间距(像素)

var angle_step = total_spread_angle / (pellet_count - 1) if pellet_count > 1 else 0    # 计算每颗子弹的角度间隔




var current_bullet_count = 0 # 当前子弹数量
var current_rof_tick = 0

const reload_audio = [
	"res://audio/wpn_reload_start.mp3","res://audio/wpn_reload_end.mp3"
]

@onready var sprite = $Sprite2D
@onready var bullet_point = $BulletPoint
@onready var fire_particles = $GPUParticles2D
@onready var audio2d = $AudioStreamPlayer2D
@onready var audio_reload = $AudioStreamPlayer2D2

var player:Player #属于某个玩家

func _ready() -> void:
	fire_particles.lifetime = weapon_rof - 0.01
	
	current_bullet_count = bullet_max
	PlayerManager.on_weapon_changed.emit(self)
	PlayerManager.on_bullet_count_changed.emit(current_bullet_count,bullet_max)
	
#射击
func shoot():
	# 获取基础方向（朝向鼠标）
	var base_dir = global_position.direction_to(get_global_mouse_position())
	var base_pos = bullet_point.global_position
	
	   # 启动协程控制子弹发射
	#await get_tree().create_timer(0.01).timeout  # 微小延迟确保动画正常触发
	
	# 计算垂直于射击方向的偏移向量
	var perpendicular_dir = base_dir.orthogonal() * parallel_spacing
	
		# 计算起始偏移位置
	var start_offset = perpendicular_dir * ((parallel_bullets - 1) / 2.0)
	
	for i in range(pellet_count):
		var delay_time = randf_range(min_delay, max_delay)
		#await get_tree().create_timer(delay_time).timeout  # Godot 4计时器语法
		for j in range(parallel_bullets):
			
			
			var instance = _pre_bullet.instantiate()
			instance.global_position = bullet_point.global_position
			
			# 计算平行子弹的位置
			var offset_pos = base_pos + start_offset - perpendicular_dir * j
			
			"""
			# 添加随机微小偏移
			var random_angle = randf_range(-random_offset, random_offset)
			#var offset_angle = -total_spread_angle/2 + i * angle_step +random_angle
			var offset_angle = -total_spread_angle/2 + randf_range(0,pellet_count-1) * angle_step +random_angle
			# 计算当前子弹的偏移角度（从-90°到+90°均匀分布）
			if pellet_count <= 1:
				offset_angle = 0
			"""
			var offset_angle = get_offset_angle(i)
			# 旋转基础方向得到当前子弹方向
			var rotated_dir = base_dir.rotated(offset_angle)
			
			instance.global_position = offset_pos
			instance.dir = rotated_dir
			instance.current_weapon = self

			get_tree().root.add_child(instance)
	
	current_bullet_count -= pellet_count * parallel_bullets
	PlayerManager.on_bullet_count_changed.emit(current_bullet_count,bullet_max)
	if current_bullet_count <= 0:
		reload()
	weapon_anim()

func get_offset_angle(index:int)->float:
	var offset_angle =0.0
	if pellet_count <= 1:
		return offset_angle
	var chaos_number =index
	if chaos_bullet>randf_range(0,1):
		chaos_number = randf_range(0,pellet_count-1)
	# 添加随机微小偏移
	var random_angle = randf_range(-random_offset, random_offset)

	offset_angle = -total_spread_angle/2 + chaos_number * angle_step +random_angle
	# 计算当前子弹的偏移角度（从-90°到+90°均匀分布）

	return offset_angle


func weapon_anim():
	fire_particles.restart()
	
	var tween = create_tween().set_ease(Tween.EASE_IN)
	tween.tween_property(sprite,"scale:x",0.7,weapon_rof / 2)
	tween.tween_property(sprite,"scale:x",1,weapon_rof / 2)
	
	audio2d.play()
	
	Game.camera_offset(Vector2(-1.5,2),weapon_rof)

# 换弹
func reload():
	audio_reload.stream = load(reload_audio[0])
	audio_reload.play()
	PlayerManager.on_weapon_reload.emit()
	
	await get_tree().create_timer(2 - 0.42).timeout
	audio_reload.stream = load(reload_audio[1])
	audio_reload.play()
	
	await get_tree().create_timer(0.42).timeout # 模拟换弹需要2秒
	current_bullet_count = bullet_max
	PlayerManager.on_bullet_count_changed.emit(current_bullet_count,bullet_max)

func _process(delta: float) -> void:
	current_rof_tick += delta
	if Input.is_action_pressed("fire") and current_rof_tick >= weapon_rof && current_bullet_count > 0:
		shoot()
		current_rof_tick = 0
